// pages/sale-ticket-detail/sale-ticket-detail.js
const request = require('../../utils/request')
const util = require('../../utils/util')
const dateFormatter = require('../../utils/dateFormatter')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkInfo: {},
    photos: [], // 现场照片
    remark: "", // 核查备注
    isEditing: false, // 是否处于编辑模式
    editData: {}, // 编辑时的临时数据
    showPreview: false, // 控制预览模态框显示
    previewData: {}, // 预览数据
    showSourceModal: false,
    sourceId: null, // 溯源ID
    sourceData: null,
    timelineData: [], // 时间轴数据
    // 商品搜索相关
    showGoodsSearchResults: false, // 控制商品搜索结果显示
    goodsSearchResults: [], // 商品搜索结果
    activeGoodsIndex: -1, // 当前激活的商品索引
    goodsSearchTimer: null // 商品搜索防抖定时器
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    const id = options.id
    if (!id) return

    wx.showLoading({ title: '加载中...' })
    request.get('/admin-api/system/goods-sales-licens/get?id=' + id)
      .then(res => {
        wx.hideLoading()
        if (res.code === 0 && res.data) {
          const data = res.data

          // 状态映射：支持 state (0/1/2) 或 status 字符串
          const s = (data.state != null ? String(data.state) : (data.status || '')).toLowerCase()
          let statusText = '待审核'
          let statusColor = '#FFA000'
          if (s === '1' || s === 'pass' || s === '审核通过') { statusText = '审核通过'; statusColor = '#07C160' }
          if (s === '2' || s === 'refuse' || s === '审核拒绝') { statusText = '审核拒绝'; statusColor = '#F44336' }

          // 优先使用后端提交字段 goodsSalesLicensDetailSaveReqVOS（大小写多变），兼容历史字段
          const details = data.goodsSalesLicensDetailSaveReqVOS || data.GoodsSalesLicensDetailSaveReqVO || data.details || data.list || []

          const checkInfo = {
            id: data.id,
            merchantId: data.merchantId || data.merchant || '',
            merchantName: data.merchantName || (data.merchant && data.merchant.name) || '',
            customerName: data.customerName || '', // 申报人名称
            customerId: data.customerId || '', // 申报人ID
            submitTime: util.formatYMDHMS(data.createTime) || '',
            auditTime: util.formatYMDHMS(data.okDate) || '',
            // 商户地址和电话（优先从 data 直接获取，兼容从 merchant 对象获取）
            address: data.address || (data.merchant && data.merchant.address) || '',
            phone: data.phone || (data.merchant && data.merchant.phone) || '',
            // 备注字段
            remark: data.remark || data.note || '',
            refuseRemark: data.refuseRemark || '', // 拒绝原因
            isShared: false,
            isLicens: !!data.isLicens,
            isCheck: !!data.isCheck,
            state: data.state != null ? data.state : (data.status || 0), // 保存原始状态值
            statusText,
            statusColor,
            // 保存原始时间戳用于预览
            createTime: data.createTime,
            okDate: data.okDate,
            // 销售凭证编号和批次号
            saleCode: data.saleCode || '',
            aboutOrder: data.aboutOrder || '',
            // 将后端的 prodName/prodCount 映射为模板使用的 name/quantity
            products: (details || []).map(d => ({
              goodsId: d.goodsId || d.id || '',
              name: d.prodName || d.name || d.goodsName || '',
              quantity: d.prodCount || d.quantity || d.count || '',
              unit: d.prodUnit || d.unit || '',
              origin: d.origin || '',
              certificateUrl: d.certificateUrl || d.certificateUrl || ''
            }))
          }
          
          this.setData({
            checkInfo,
            // 如果不是审核通过，则默认进入编辑模式
            isEditing: (statusText !== '审核通过'),
            editData: JSON.parse(JSON.stringify(checkInfo)) // 深拷贝用于编辑
          })
        } else {
          wx.showToast({ title: '未找到数据', icon: 'none' })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('获取申报详情失败', err)
        wx.showToast({ title: '加载失败', icon: 'none' })
      })
  },

  navigateBack() {
    wx.navigateBack()
  },

  // 编辑模式相关方法
  onRemarkChange(e) {
    this.setData({ 'editData.remark': e.detail.value })
  },

  // 申报人姓名修改（编辑时）
  onCustomerNameChange(e) {
    this.setData({ 'editData.customerName': e.detail.value })
  },

  toggleCheckbox(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`editData.${field}`]: !this.data.editData[field]
    })
  },

  onProductChange(e) {
    const index = e.currentTarget.dataset.index
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`editData.products[${index}].${field}`]: value
    })
  },

  // ========== 商品搜索相关方法 ==========
  // 商品搜索输入
  onGoodsSearchInput(e) {
    const index = e.currentTarget.dataset.index
    const value = e.detail.value.trim()
    
    // 更新当前商品名称
    this.setData({
      [`editData.products[${index}].name`]: value,
      showGoodsSearchResults: true,
      activeGoodsIndex: index
    })

    // 清除之前的定时器
    if (this.data.goodsSearchTimer) {
      clearTimeout(this.data.goodsSearchTimer)
    }

    // 如果输入为空，清空搜索结果
    if (!value) {
      this.setData({ goodsSearchResults: [] })
      return
    }

    // 设置防抖：300ms 后自动搜索
    const timer = setTimeout(() => {
      this.searchGoods(value)
    }, 300)

    this.setData({ goodsSearchTimer: timer })
  },

  // 搜索商品
  searchGoods(keyword) {
    if (!keyword) {
      this.setData({ goodsSearchResults: [] })
      return
    }

    const params = { keyword }

    request.get('/admin-api/system/goods-info/getList', params)
      .then(res => {
        if (res.code === 0 && res.data) {
          const list = Array.isArray(res.data) ? res.data : (res.data.list || res.data.items || [])
          this.setData({
            goodsSearchResults: list
          })
        } else {
          this.setData({ goodsSearchResults: [] })
        }
      })
      .catch(err => {
        console.error('商品搜索失败', err)
        this.setData({ goodsSearchResults: [] })
      })
  },

  // 选择商品
  selectGoods(e) {
    const item = e.currentTarget.dataset.item
    const { activeGoodsIndex } = this.data
    
    if (activeGoodsIndex === -1 || activeGoodsIndex >= this.data.editData.products.length) {
      console.error('无效的商品索引')
      return
    }

    this.setData({
      [`editData.products[${activeGoodsIndex}].goodsId`]: item.id,
      [`editData.products[${activeGoodsIndex}].name`]: item.name,
      [`editData.products[${activeGoodsIndex}].unit`]: item.unit || '',
      showGoodsSearchResults: false,
      goodsSearchResults: [],
      activeGoodsIndex: -1
    })
  },

  // 隐藏商品搜索结果
  hideGoodsSearchResult() {
    this.setData({
      showGoodsSearchResults: false,
      goodsSearchResults: [],
      activeGoodsIndex: -1
    })
  },

  addProduct() {
    const products = [...this.data.editData.products, { goodsId: '', name: '', quantity: '', unit: '', origin: '', certificateUrl: '' }]
    this.setData({ 'editData.products': products })
  },

  deleteProduct(e) {
    const index = e.currentTarget.dataset.index
    if (this.data.editData.products.length <= 1) {
      wx.showToast({ title: '至少保留一个商品', icon: 'none' })
      return
    }
    const products = [...this.data.editData.products]
    products.splice(index, 1)
    this.setData({ 'editData.products': products })
  },

  // 保存编辑
  saveEdit() {
    const { editData } = this.data
    
    // 验证必填项
    if (!editData.merchantId) {
      wx.showToast({ title: '商户信息缺失', icon: 'none' })
      return
    }
    
    // 验证商品明细
    if (!editData.products || editData.products.length === 0) {
      wx.showToast({ title: '请至少添加一个商品', icon: 'none' })
      return
    }
    
    // 验证商品字段
    for (let i = 0; i < editData.products.length; i++) {
      if (!editData.products[i].name || !editData.products[i].quantity) {
        wx.showToast({ title: `请完善商品${i + 1}的信息`, icon: 'none' })
        return
      }
    }

    // 构造提交数据（与申报页 create 接口字段一致，增加 id 和 state）
    const submitData = {
      id: editData.id,
      merchantId: editData.merchantId,
      merchantName: editData.merchantName,
      customerId: editData.customerId || '',
      customerName: editData.customerName || '',
      address: editData.address,
      phone: editData.phone,
      remark: editData.remark || '',
      isLicens: editData.isLicens,
      isCheck: editData.isCheck,
      state: editData.state != null ? editData.state : 0, // 添加状态字段
      goodsSalesLicensDetailSaveReqVOS: editData.products.map(item => ({
        prodName: item.name,
        prodCount: item.quantity,
        prodUnit: item.unit || '',
        goodsId: item.goodsId || ''
      }))
    }

    wx.showLoading({ title: '保存中...' })
    request.put('/admin-api/system/goods-sales-licens/update', submitData)
      .then(res => {
        wx.hideLoading()
        if (res.code === 0) {
          wx.showToast({ title: '保存成功', icon: 'success' })
          // 刷新上一页
          try {
            const pages = getCurrentPages()
            if (pages && pages.length >= 2) {
              const prev = pages[pages.length - 2]
              if (prev && typeof prev.loadApplications === 'function') {
                prev.setData({ pageNo: 1, checkList: [] })
                prev.loadApplications(false).catch(() => {})
              }
            }
          } catch (e) {
            // ignore
          }
          // 重新加载当前页
          setTimeout(() => {
            const id = this.data.checkInfo.id
            if (id) {
              request.get('/admin-api/system/goods-sales-licens/get?id=' + id)
                .then(response => {
                  if (response.code === 0 && response.data) {
                    const data = response.data
                    const s = (data.state != null ? String(data.state) : (data.status || '')).toLowerCase()
                    let statusText = '待审核'
                    let statusColor = '#FFA000'
                    if (s === '1' || s === 'pass' || s === '审核通过') { statusText = '审核通过'; statusColor = '#07C160' }
                    if (s === '2' || s === 'refuse' || s === '审核拒绝') { statusText = '审核拒绝'; statusColor = '#F44336' }
                    const details = data.goodsSalesLicensDetailSaveReqVOS || data.GoodsSalesLicensDetailSaveReqVO || data.details || data.list || []
                    const checkInfo = {
                      id: data.id,
                      merchantId: data.merchantId || data.merchant || '',
                      merchantName: data.merchantName || (data.merchant && data.merchant.name) || '',
                      customerName: data.customerName || '', // 申报人名称
                      customerId: data.customerId || '', // 申报人ID
                      submitTime: util.formatYMDHMS(data.createTime) || '',
                      auditTime: util.formatYMDHMS(data.okDate) || '',
                      address: data.address || '',
                      phone: data.phone || '',
                      remark: data.remark || data.note || '',
                      refuseRemark: data.refuseRemark || '', // 拒绝原因
                      isShared: false,
                      isLicens: !!data.isLicens,
                      isCheck: !!data.isCheck,
                      state: data.state != null ? data.state : (data.status || 0),
                      statusText,
                      statusColor,
                      products: (details || []).map(d => ({
                        goodsId: d.goodsId || d.id || '',
                        name: d.prodName || d.name || d.goodsName || '',
                        quantity: d.prodCount || d.quantity || d.count || '',
                        unit: d.prodUnit || d.unit || '',
                        origin: d.origin || '',
                        certificateUrl: d.certificateUrl || d.certificateUrl || ''
                      }))
                    }
                    this.setData({
                      checkInfo,
                      isEditing: (statusText !== '审核通过'),
                      editData: JSON.parse(JSON.stringify(checkInfo))
                    })
                  }
                })
            }
          }, 800)
        } else {
          wx.showToast({ title: res.msg || '保存失败', icon: 'none' })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('保存失败', err)
        wx.showToast({ title: '保存失败', icon: 'none' })
      })
  },

  cancelEdit() {
    // 恢复编辑数据为原始数据
    this.setData({
      editData: JSON.parse(JSON.stringify(this.data.checkInfo))
    })
    wx.showToast({ title: '已取消编辑', icon: 'none' })
  },

  // 预览销售凭证
  previewDocument() {
    const detail = this.data.checkInfo
    if (!detail) return
    
    // 格式化申报时间 (createTime)
    const createDateParts = dateFormatter.formatToYearMonthDay(detail.createTime)
    
    // 格式化开票时间 (审核时间 okDate)
    const okDateParts = dateFormatter.formatToYearMonthDay(detail.okDate)
    
    this.setData({
      previewData: {
        saleCode: detail.saleCode || '',
        customerName: detail.customerName || '',
        address: detail.address || '',
        phone: detail.phone || '',
        products: detail.products || [],
        saleCode: detail.saleCode || '',
        aboutOrder: detail.aboutOrder || '',
        isLicens: detail.isLicens || false,
        isCheck: detail.isCheck || false,
        createYear: createDateParts.year,
        createMonth: createDateParts.month,
        createDay: createDateParts.day,
        okYear: okDateParts.year,
        okMonth: okDateParts.month,
        okDay: okDateParts.day
      },
      showPreview: true
    })
  },

  // 关闭预览
  closePreview() {
    this.setData({ showPreview: false })
  },

  // 从时间轴预览销售凭证
  previewFromTimeline(e) {
    const item = e.detail.item
    if (!item || item.type !== 'sales') return
    console.log(item,1111);
    
    const createDateParts = dateFormatter.formatToYearMonthDay(item.createTime)
    const okDateParts = dateFormatter.formatToYearMonthDay(item.okDate)
    
    this.setData({
      previewData: {
        saleCode: item.saleCode || '',
        customerName: item.customerName || '',
        address: item.address || '',
        phone: item.phone || '',
        aboutOrder: item.aboutOrder || '',
        products: item.products || [],
        isLicens: item.isLicens || false,
        isCheck: item.isCheck || false,
        createYear: createDateParts.year,
        createMonth: createDateParts.month,
        createDay: createDateParts.day,
        okYear: okDateParts.year,
        okMonth: okDateParts.month,
        okDay: okDateParts.day
      },
      showPreview: true
    })
  },

  // 查看合格证图片
  previewCertificate(e) {
    const url = e.currentTarget.dataset.url
    const item = e.currentTarget.dataset.item
    if (!url) return
    
    const urls = item && item.certificates ? item.certificates : [url]
    wx.previewImage({
      current: url,
      urls: urls
    })
  },

  // 防止点击穿透
  preventClose() {},

  // 隐藏溯源弹窗
  hideSourceModal() {
    this.setData({ showSourceModal: false })
  },

  // 调用溯源接口并展示结果（显示组件弹窗）
  fetchSource() {
    const id = this.data.checkInfo && this.data.checkInfo.id;
    console.log('sale-ticket-detail: 显示溯源弹窗, checkInfo.id=', id);
    if (!id) {
      wx.showToast({ title: '未找到可溯源的ID', icon: 'none' });
      return;
    }
    // 新方案：先显示弹窗，再通过组件方法加载数据
    this.setData({ showSourceModal: true }, () => {
      console.log('sale-ticket-detail: 弹窗已显示，准备调用组件方法');
      // 获取组件实例并调用 open 方法
      const sourceTimeline = this.selectComponent('#sourceTimeline');
      if (sourceTimeline) {
        console.log('sale-ticket-detail: 找到组件实例，调用 open 方法, id=', id);
        sourceTimeline.open(id);
      } else {
        console.error('sale-ticket-detail: 未找到组件实例');
      }
    });
  },

  // 旧版溯源方法（保留作为后备）
  async fetchSourceOld() {
    const checkInfo = this.data.checkInfo || {}
    const id = checkInfo.id || this.data.id
    if (!id) {
      wx.showToast({ title: '未找到可溯源的ID', icon: 'none' })
      return
    }

    try {
      wx.showLoading({ title: '查询中...' })
      const res = await request.get('/admin-api/system/goods-sales-licens/source', { id })
      wx.hideLoading()
      
      if (res.code !== 0 || !res.data || !res.data.list || res.data.list.length === 0) {
        wx.showToast({ title: '暂无溯源数据', icon: 'none' })
        return
      }

      const sourceData = res.data.list[0] || {}
      const timelineData = []

      // 1. 预约时间 - 显示合格证图片
      const orderApply = sourceData.orderApplyWithCheckInfoVOS && sourceData.orderApplyWithCheckInfoVOS[0]
      if (orderApply && orderApply.orderApplySaveReqVO) {
        const order = orderApply.orderApplySaveReqVO
        const planArriveTime = order.planArriveTime
        if (planArriveTime) {
          const timestamp = typeof planArriveTime === 'number' ? planArriveTime : new Date(planArriveTime).getTime()
          const certificateImages = []
          
          // 遍历所有商品，收集每个商品的合格证图片
          const applyDetails = orderApply.applyDetailSaveReqVOS || []
          applyDetails.forEach(detail => {
            if (detail.certification) {
              certificateImages.push(...detail.certification.split(',').filter(img => img && img.trim()))
            }
          })

          timelineData.push({
            time: timestamp,
            timeText: dateFormatter.formatTimestamp(timestamp),
            title: '进场登记',
            type: 'order',
            certificates: certificateImages
          })
        }
      }

      // 2. 核验时间 - 显示核验人
      if (orderApply && orderApply.orderApplySaveReqVO) {
        const order = orderApply.orderApplySaveReqVO
        const checkTime = order.checkTime
        console.log('核验时间 checkTime:', checkTime)
        console.log('完整 order 数据:', order)
        
        if (checkTime) {
          const timestamp = typeof checkTime === 'number' ? checkTime : new Date(checkTime).getTime()
          console.log('核验时间 timestamp:', timestamp)
          timelineData.push({
            time: timestamp,
            timeText: dateFormatter.formatTimestamp(timestamp),
            title: '门岗核验',
            type: 'check',
            checkUser: order.checkUser || '未知'
          })
        }
      }

      // 3. 检测时间 - 显示合格状态和检测指标结果
      if (orderApply && orderApply.orderApplySaveReqVO) {
        const order = orderApply.orderApplySaveReqVO
        const testTime = order.testTime
        if (testTime) {
          const timestamp = typeof testTime === 'number' ? testTime : new Date(testTime).getTime()
          const checkInfoList = orderApply.checkInfo || []
          
          // 判断整体合格状态
          const allPassed = checkInfoList.every(item => {
            const state = String(item.state || '0')
            return state === '0' || state === 'pass'
          })

          timelineData.push({
            time: timestamp,
            timeText: dateFormatter.formatTimestamp(timestamp),
            title: '抽样检测',
            type: 'test',
            status: allPassed ? '检测合格' : '检测异常',
            statusColor: allPassed ? '#07C160' : '#F44336',
            expanded: false,  // 初始化为收起状态
            testResults: checkInfoList.map(item => ({
              name: item.name || '',
              value: item.value !== null && item.value !== undefined ? item.value : '-',
              safeValue: item.safeValue || '',
              state: String(item.state || '0'),
              stateText: (String(item.state || '0') === '0' || String(item.state || '0') === 'pass') ? '合格' : '不合格',
              stateColor: (String(item.state || '0') === '0' || String(item.state || '0') === 'pass') ? '#07C160' : '#F44336'
            }))
          })
        }
      }

      // 4. 销售凭证申请时间 - 显示预览按钮
      const salesInfo = sourceData.goodsSalesLicensSaveReqVO
      if (salesInfo && salesInfo.createTime) {
        const timestamp = typeof salesInfo.createTime === 'number' ? salesInfo.createTime : new Date(salesInfo.createTime).getTime()
        const salesDetails = sourceData.salesLicensDetailSaveReqVOS || []
        
        timelineData.push({
          time: timestamp,
          timeText: dateFormatter.formatTimestamp(timestamp),
          title: '销售合格证',
          type: 'sales',
          merchantName: salesInfo.merchantName || '',
          products: salesDetails.map(d => ({
            name: d.prodName || '',
            quantity: d.prodCount || ''
          })),
          isLicens: !!salesInfo.isLicens,
          isCheck: !!salesInfo.isCheck,
          createTime: salesInfo.createTime,
          okDate: salesInfo.okDate
        })
      }

      // 按时间顺序排列（最早的在最上面）
      timelineData.sort((a, b) => a.time - b.time)

      console.log('最终 timelineData:', timelineData)
      console.log('timelineData 长度:', timelineData.length)

      this.setData({ 
        showSourceModal: true, 
        sourceData,
        timelineData 
      })
    } catch (err) {
      wx.hideLoading()
      console.error('fetchSource error', err)
      wx.showToast({ title: '溯源查询失败', icon: 'none' })
    }
  },

  // 切换检测结果展开/收起状态
  toggleTestResults(e) {
    const index = e.currentTarget.dataset.index
    const item = this.data.timelineData[index]
    if (item && item.type === 'test') {
      this.setData({
        ['timelineData[' + index + '].expanded']: !item.expanded
      })
    }
  },

  // 删除申报单
  deleteApplication() {
    const id = this.data.checkInfo && this.data.checkInfo.id
    if (!id) {
      wx.showToast({ title: '缺少申报单ID', icon: 'none' })
      return
    }

    wx.showModal({
      title: '确认删除',
      content: '删除后将无法恢复，确定要删除该申报单吗？',
      confirmText: '删除',
      confirmColor: '#F44336',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          request.delete('/admin-api/system/goods-sales-licens/delete?id=' + id)
            .then(resp => {
              wx.hideLoading()
              if (resp.code === 0) {
                wx.showToast({ title: '删除成功', icon: 'success' })
                // 触发上一页刷新（如果上一页实现了 loadApplications）
                try {
                  const pages = getCurrentPages()
                  if (pages && pages.length >= 2) {
                    const prev = pages[pages.length - 2]
                    if (prev && typeof prev.loadApplications === 'function') {
                      // 重置上一页分页并刷新
                      prev.setData({ pageNo: 1, checkList: [] })
                      prev.loadApplications(false).catch(() => {})
                    }
                  }
                } catch (e) {
                  // ignore
                }
                setTimeout(() => wx.navigateBack(), 800)
              } else {
                wx.showToast({ title: resp.msg || '删除失败', icon: 'none' })
              }
            })
            .catch(err => {
              wx.hideLoading()
              console.error('删除失败', err)
              wx.showToast({ title: '删除失败', icon: 'none' })
            })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})